package cn.zyq.ykb.service.task.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.zyq.ykb.beans.task.Task;
import cn.zyq.ykb.beans.task.TaskAudit;
import cn.zyq.ykb.beans.user.User;
import cn.zyq.ykb.mapper.task.TaskAuditMapper;
import cn.zyq.ykb.mapper.task.TaskMapper;
import cn.zyq.ykb.system.common.BaseService;
import cn.zyq.ykb.system.enums.core.ResponseCodeEnum;
import cn.zyq.ykb.system.enums.core.TaskOrderStateEnum;
import cn.zyq.ykb.system.enums.core.TaskOrderTypeEnum;
import cn.zyq.ykb.system.enums.core.TaskStateEnum;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.task.delayQueue.DelayQueueManager;
import cn.zyq.ykb.system.task.delayQueue.DelayTask;
import cn.zyq.ykb.system.task.delayQueue.TaskBase;
import cn.zyq.ykb.system.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.mapper.task.TaskOrderMapper;
import cn.zyq.ykb.beans.task.TaskOrder;
import cn.zyq.ykb.service.task.TaskOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.zyq.ykb.system.common.PageParam;
import com.github.pagehelper.PageInfo;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务-订单Service业务层处理
 *
 * @author SystemAuth
 * @date 2023-05-25
 */
@Service
@Slf4j
public class TaskOrderServiceImpl  extends BaseService implements TaskOrderService {

    @Autowired
    private TaskOrderMapper taskOrderMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskAuditMapper taskAuditMapper;
    @Autowired
    private DelayQueueManager delayQueueManager;
    /**
     * 查询任务-订单
     *
     * @param taskOrderID 任务-订单主键
     * @return 任务-订单
     */
    @Override
    public TaskOrder selectTaskOrderByTaskOrderID(Integer taskOrderID) {
        TaskOrder taskOrder = taskOrderMapper.selectByPrimaryKey(taskOrderID);
        if (taskOrder.getDeleted() == 1) {
            return null;
        }
        return taskOrder;
    }

    /**
     * 查询任务-订单
     *
     * @param serviceID 业务ID
     * @return 任务-订单
     */
    @Override
    public TaskOrder selectTaskOrderByServiceID(String serviceID) {
        TaskOrder param = new TaskOrder();
        param.setDeleted(0);
        param.setServiceID(serviceID);
        return this.taskOrderMapper.selectOne(param);
    }

    /**
     * 查询任务-订单列表
     *
     * @param pageParam
     * @return 任务-订单
     */
    @Override
    public PageInfo<TaskOrder> selectTaskOrderList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<TaskOrder> list = this.taskOrderMapper.list(pageParam.getKv());
        return new PageInfo<>(list);
    }

    /**
     * 查询任务-订单列表
     *
     * @param param
     * @return 任务-订单
     */
    @Override
    public List<TaskOrder> selectTaskOrderList(TaskOrder param) {
        param.setDeleted(0);
        return this.taskOrderMapper.select(param);
    }
    /**
     * 新增任务-订单
     *
     * @param param 任务-订单
     * @return 结果
     */
    @Override
    public int insertTaskOrder(TaskOrder param) {
        this.setCreateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.taskOrderMapper.insertSelective(param);
    }

    /**
     * 修改任务-订单
     *
     * @param param 任务-订单
     * @return 结果
     */
    @Override
    public int updateTaskOrder(TaskOrder param) {
        this.setUpdateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.taskOrderMapper.updateByPrimaryKeySelective(param);
    }

    /**
     * 批量删除任务-订单
     *
     * @param taskOrderIDs 需要删除的任务-订单主键
     * @return 结果
     */
    @Override
    public int deleteTaskOrderByTaskOrderIDs(Integer[] taskOrderIDs) {
        int i = 0;
        for (Integer taskOrderID : taskOrderIDs) {
            i += this.deleteTaskOrderByTaskOrderID(taskOrderID);
        }
        return i;
    }

    /**
     * 删除任务-订单信息
     *
     * @param taskOrderID 任务-订单主键
     * @return 结果
     */
    @Override
    public int deleteTaskOrderByTaskOrderID(Integer taskOrderID) {
        TaskOrder taskOrder = this.selectTaskOrderByTaskOrderID(taskOrderID);
        if (taskOrder == null) {
            return 0;
        } else {
            TaskOrder storeInfo = new TaskOrder();
            storeInfo.setTaskOrderID(taskOrderID);
            storeInfo.setDeleted(1);
            storeInfo.setUpdateBy(SecurityUtils.getSysAdminID());
            storeInfo.setUpdateTime(LocalDateTime.now());
            this.taskOrderMapper.updateByPrimaryKeySelective(storeInfo);
            return 1;
        }
    }
    @Override
    public TaskOrder payTask(TaskOrder param, HttpServletRequest request, User loginUser) {
//        log.info("支付总金额数据：{}",param);
//        Integer taskID = param.getTaskID();
//        Task task = this.taskMapper.selectByPrimaryKey(taskID);
//        if (BeanUtil.isEmpty(task)){
//            throw new BusinessException(ResponseCodeEnum.ERROR,"该任务信息不存在，暂不能支付");
//        }
//        if (task.getTaskState().equals(TaskStateEnum.DZF.getValue())){
//            throw new BusinessException(ResponseCodeEnum.ERROR,"该任务不是待支付状态,暂不能支付");
//        }
//        param.setTaskID(task.getTaskID());
//        param.setTaskNum(task.getNumber());
//        param.setTaskPrice(task.getPrice());
//        param.setTotalPrice(task.getPrice().multiply(new BigDecimal(task.getNumber())));
//        param.setOrderType(TaskOrderTypeEnum.FBRW.getValue());
//        param.setOrderState(TaskOrderStateEnum.DZF.getValue());
//        param.setPayTime(LocalDateTime.now());
//        String orderCode = loginUser.getPhone() + "-" + System.currentTimeMillis();
//        param.setOrderCode(orderCode);
//        this.setCreateBaseData(param,loginUser);
//        this.taskOrderMapper.insertSelective(param);
//        //生成支付订单

        return null;
    }

    @Override
    public void checkExpire(String serviceID) {
        TaskOrder taskOrder = this.selectTaskOrderByServiceID(serviceID);
        if (BeanUtil.isEmpty(taskOrder)){
            throw new BusinessException(ResponseCodeEnum.ERROR,"该任务订单不存在");
        }
        //查询任务
        Task task = this.taskMapper.selectByPrimaryKey(taskOrder.getTaskID());
        //查询任务审核表
        TaskAudit taskAudit = new TaskAudit();
        taskAudit.setAudit(1);
        taskAudit.setTaskID(task.getTaskID());
        TaskAudit taskAudit1 = this.taskAuditMapper.selectOne(taskAudit);
        if (taskOrder.getOrderType().equals(TaskOrderStateEnum.DZF.getValue())){
            if (LocalDateTime.now().isAfter(taskOrder.getPayExpireTime())
                    || LocalDateTime.now().equals(taskOrder.getPayExpireTime())) {
                //已过期
                log.info("订单{}已被处理为延时未支付", taskOrder.getServiceID());
                TaskOrder updateOrder = new TaskOrder();
                updateOrder.setOrderState(TaskOrderStateEnum.ZFCS.getValue());
                updateOrder.setTaskOrderID(taskOrder.getTaskOrderID());
                this.taskOrderMapper.updateByPrimaryKeySelective(updateOrder);
                if (taskOrder.getOrderType().equals(TaskOrderTypeEnum.FBRW.getValue())) {
                    //如果是任务发布  修改订单状态为未成功
                    task.setTaskState(TaskStateEnum.WCG.getValue());
                }else if(taskOrder.getOrderType().equals(TaskOrderTypeEnum.XGDJ.getValue())){
                    task.setPrice(taskAudit1.getPrice());
                    task.setTaskState(taskAudit1.getState());
                    task.setPayMent(new BigDecimal(0));
                }else if(taskOrder.getOrderType().equals(TaskOrderTypeEnum.ZJSL.getValue())){
                    task.setNumber(taskAudit1.getNumber());
                    task.setTaskState(taskAudit1.getState());
                    task.setPayMent(new BigDecimal(0));
                }else {

                }
                this.taskMapper.updateByPrimaryKeySelective(task);
            }
        }else {
            //重新加回队列
            TaskBase base = new TaskBase(taskOrder.getServiceID(), 1, taskOrder.getServiceID());
            //获取相差时间
            long l = DateUtils.durationToMillis(LocalDateTime.now(), taskOrder.getPayExpireTime());
            if (l > 0) {
                DelayTask task2 = new DelayTask(base, l);
                this.delayQueueManager.put(task2);
            }
        }
    }

    @Override
    public void reloadStateQueue() {
        log.info("初始化未支付任务订单进入延时队列");
        PageParam pageParam = new PageParam();
        pageParam.setPage(1);
        pageParam.setPageSize(1000);
        boolean flag = true;
        while (flag) {
            //获取未支付的数据
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            List<TaskOrder> list = this.taskOrderMapper.queryNoPayOrder();
            for (TaskOrder order : list) {
                if (LocalDateTime.now().isBefore(order.getPayExpireTime())) {
                    //加入延时队列
                    TaskBase base = new TaskBase(order.getServiceID(), 1, order.getServiceID());
                    long l = DateUtils.durationToMillis(LocalDateTime.now(), order.getPayExpireTime());
                    //获取相差时间
                    DelayTask task = new DelayTask(base, l);
                    this.delayQueueManager.put(task);
                    log.info("订单：{}加入延时队列，延时毫秒{}，过期时间：{}", order.getServiceID(), l, order.getPayExpireTime());
                } else {
                    log.info("订单：{}已过期", order.getServiceID());
                    //已过期
                    TaskOrder updateOrder = new TaskOrder();
                    updateOrder.setOrderState(TaskOrderStateEnum.ZFCS.getValue());
                    updateOrder.setTaskOrderID(order.getTaskOrderID());
                    this.taskOrderMapper.updateByPrimaryKeySelective(updateOrder);
                    //回滚数量
                        Task task = this.taskMapper.selectByPrimaryKey(order.getTaskID());
                        this.taskMapper.updateSoldNum(task.getResidueNumber(), +order.getTaskNum(), task.getTaskID());
                }
            }
            //当获取的列表小于分页大小，则没有更多数据，停止轮询
            if (list.size() < pageParam.getPageSize()) {
                flag = false;
            } else {
                pageParam.setPage(pageParam.getPage() + 1);
            }
        }
    }

}
